<template>
  <h1 style="width: 100%; text-align: center; margin-bottom: 30px">商品属性</h1>
  <CategoryList :disabled="!isShow"/>
  <div style="margin-top: 30px">
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <template #header v-if="isShow">
        <el-button
          type="success"
          size="default"
          :icon="Plus"
          @click="addAttr"
        >新增属性
        </el-button>
      </template>
      <el-table border stripe :data="tableDate" v-if="isShow">
        <el-table-column label="序号" type="index" width="80"/>
        <el-table-column label="属性名称" width="150" prop="attrName"></el-table-column>
        <el-table-column label="属性值名称列表" prop="attrValueList">
          <template #default="{row}">
            <el-tag
              round
              type="danger"
              hit
              v-for="item in row.attrValueList"
              :key="item.id"
              :style="{marginRight:'5px'}"
            >{{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{row}">
            <el-button type="warning" :icon="Edit" @click="editAttr(row)"/>
            <el-popconfirm title="Are you sure to 删除 this?" @confirm="deleteListItem(row)">
              <template #reference>
                <el-button type="danger" :icon="Delete"/>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div v-else>
        <el-form label-width="80px" :inline="true">
          <el-form-item label="属性名">
            <el-input
              placeholder="请输入属性名"
              v-model="newAttrData.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <div>
          <el-button type="primary" @click="addAttrValue" :disabled="!newAttrData.attrName">添加属性值</el-button>
          <el-button type="default" @click="cancle">取消</el-button>
        </div>
        <el-table border stripe style="margin-top: 30px" :data="newAttrData.attrValueList">
          <el-table-column type="index" width="50" label="序号"/>
          <el-table-column label="属性值名称" prop="valueName">
            <template v-slot="{row,$index}">
              <el-input
                placeholder="请添加新的属性值"
                size="default"
                v-model="row.valueName"
                v-if="row.isEdit"
                @blur="toLook(row,$index)"
                ref = 'writeInput'
                @focus="saveOldValue(row)"
              />
              <p
                v-else
                @click="toUpdate(row)"
                style="width: 100%;"
              >{{ row.valueName }}</p>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{$index}">
              <el-button type="danger" :icon="Delete" @click="deleteItem($index)"/>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 30px">
          <el-button
            type="primary"
            @click="saveAttr"
            :disabled="newAttrData.attrValueList.length <= 0 || !newAttrData.attrName"
          >保存</el-button>
          <el-button type="default" @click="cancle">取消</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
import {defineComponent} from 'vue';

export default defineComponent({
  name: 'Attr',
});
</script>
<script setup lang="ts">
import {Plus, Edit, Delete} from '@element-plus/icons';
import {ref, watch , nextTick} from 'vue';
import CategoryList from '@/components/CategoryList/CategoryList.vue';
import type {attrListType, attrListValueType,attrValueItemType} from '@/api/attr';
import useAttrStore from '@/stores/attr';
import {storeToRefs} from 'pinia';
import {requestAttrList,requestUpdateOrAddAttr,requestDeleteAttr} from '@/api/attr';
import cloneDeep from 'lodash/cloneDeep';
import {ElMessage} from 'element-plus';
//定义table对应的数据
const attrStore = useAttrStore();
const {category1Id, category2Id, category3Id} = storeToRefs(attrStore);
const tableDate = ref<attrListType>([]);
//封装获取新的属性列表的请求
const getAttrList = async () => {
  const re = await requestAttrList(category1Id.value as number, category2Id.value as number, category3Id.value as number);
  tableDate.value = re;
}

//通过监听category3Id的变化来发送请求
watch(category3Id,  (newValue) => {
  if (!newValue) {
    tableDate.value = [];
    return;
  }
  getAttrList()
  // console.log(tableDate.value);
}, {immediate: true});

const newAttrData = ref<attrListValueType>({
  attrName: '',
  categoryId: category3Id.value as number,
  categoryLevel: 3,
  attrValueList: [],
});
//获取当前input元素
const writeInput = ref()
//创建切换标签的响应式属性
const isShow = ref(true);
const addAttr = () => {
  isShow.value = false;
//  每次切换到新添加属性的页面就重置一下数据
  newAttrData.value={
    attrName: '',
    categoryId: category3Id.value as number,
    categoryLevel: 3,
    attrValueList: [],
  }
};
const cancle = () => {
  isShow.value = true;
};
//删除数据
const deleteItem = ($index:number) =>{
  newAttrData.value.attrValueList.splice($index,1)
}
//添加新的属性值的方法
const addAttrValue = () => {
  const newAttrValue = ref({
    valueName:'',
    attrId:newAttrData.value.id as number,
    isEdit:true
  })
  newAttrData.value.attrValueList.push(newAttrValue.value)
  nextTick(()=>{
    writeInput.value.focus()
  })
}
//点击修改按钮返还当前页面的值
const editAttr = (row:attrListValueType) =>{
  isShow.value = false
  const cloneRow = cloneDeep(row)
  cloneRow.attrValueList.forEach(item => {
    item.isEdit = false
  })
  newAttrData.value = cloneRow
}

let oldAttrValueName = ''
const saveOldValue= (row:attrValueItemType) =>{
  oldAttrValueName = row.valueName
}
//转到编辑模式
const toUpdate = (row:attrValueItemType) => {
  row.isEdit = true
  nextTick(()=>{
    writeInput.value.focus()
  })
}
const toLook = (row:attrValueItemType,$index:number) =>{
  row.isEdit = false
//判断输入的是否为空
  if (!row.valueName.trim()){
    if (!oldAttrValueName){
      newAttrData.value.attrValueList.splice($index,1)
    }else {
      row.valueName = oldAttrValueName;
    }
  }
//  判断是否有重复
let isRepeat = newAttrData.value.attrValueList.some(item => {
//判断是否是自己
  if (item === row) return;
  return item.valueName === row.valueName
})
  if (isRepeat){
    if (oldAttrValueName){
      row.valueName = oldAttrValueName;
    }else {
      newAttrData.value.attrValueList.splice($index,1)
    }
  }
  oldAttrValueName = "";
}

//保存数据提交请求
const saveAttr = async () =>{
  //发送数据的时候不需要isEdit所以要删除
  newAttrData.value.attrValueList.forEach(item => {
    delete item.isEdit;
  })
//  判断当前的属性值是否为空
  if (newAttrData.value.attrValueList.length <= 0)ElMessage.warning('新增或修改的数据不能为空！！');
  try {
    await requestUpdateOrAddAttr(newAttrData.value)
    ElMessage.success('修改或者新增数据成功!!!!')
    isShow.value=true
    await getAttrList()
  }catch (e){
    ElMessage.error('新增或者修改数据失败！！！')
  }
}
//删除一列
const deleteListItem = async (row:attrListValueType) => {
  try {
    await requestDeleteAttr(row.id as number)
    ElMessage.success('删除成功')
    isShow.value=true
    await getAttrList()
  }catch (e){
    ElMessage.warning('删除数据失败')
  }
}
</script>

<style scoped>

</style>